package com.xujl.hsns.codec.impl;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Arrays;

import org.apache.mina.core.buffer.CachedBufferAllocator;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.dyuproject.protostuff.JsonIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.XmlIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

public class JSONDecoder extends CumulativeProtocolDecoder {
	private final static Logger LOGGER = LoggerFactory.getLogger(JSONDecoder.class);
	Schema schema;
	Class decodeClazz;

//	 IoBuffer buffer = new CachedBufferAllocator().;
	public  JSONDecoder (Class decodeClazz){
		 this.decodeClazz= decodeClazz;
		 schema=RuntimeSchema.createFrom(decodeClazz);
	}
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		
		if (in.prefixedDataAvailable(4)) { 
            int length = in.getInt(); 
            byte[] bytes = new byte[length]; 
            in.get(bytes);
            LOGGER.debug( new String(bytes,"utf-8"));
            LOGGER.debug("bytes length:"+length);  
            Object o=JSON.parse(bytes,0,bytes.length,Charset.forName("utf-8").newDecoder(),Feature.AllowSingleQuotes);//decodeClazz.newInstance();
//        	JSON.parse(bytes,com.alibaba.fastjson.parser.Feature.AllowSingleQuotes);
//            JsonIOUtil.mergeFrom(bytes, o, schema,false);
			
			LOGGER.info(o.getClass().toString());
            out.write(o); 
           
            return true; 
        } else { 
        	 LOGGER.debug("IoBuffer"+in);
            return false; 
        }
	
	}


}
